--[[
 @classmod Command
 A Command class is used for handling different commands on the command bar.
 A command is composed of a target list (on which the command is executed)
 A command is created by returning an instance of the class Command in the form:
	Command( { name, {
	
		{ targetA, function (arg1, ... argn)
			[...]
		end
		},
		
		[...]
	
	})
	
	Target "%" is used if no targets match the given one,
	and gives all arguments to the associated function
	
@see export
@see import
]]

local lume = require(LIB_PATH.."lume")

return pl.class {
   _name = "Command",
   _init = function (self, name, target_list)
      self.name = name
      self.target_list = target_list
   end,
   
   target_exists = function (self, target)
      return lume.any(self.target_list, function (v)
			 return v[1] == target
      end)
   end,
   
   get_target_method = function (self, target)
      local method
      for k, v in ipairs(self.target_list) do
	 if v[1] == target then method = v[2] end
      end
      return method
   end,

   suggest = function (self)
      return lume.reduce(lume.map(self.target_list, function (v)
				     return v[1]
				 end), function (v1, v2)
			    return string.format("%s %s", v1, v2)
      end)
   end,
   
   execute = function (self, target, args)
      local args = args or {}
      if not target and not self:target_exists ("%") then return "no argument given" end
      if not self:target_exists (target) then
				if self:target_exists ("%") then
					return self:get_target_method ("%")(target, unpack(args))
				else
					return target .. " not found"
				end
      end
      return self:get_target_method (target)(unpack(args))
   end,
}
